package com.huzz.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huzz.entity.SysDictItem;
import com.huzz.mapper.SysDictItemMapper;
import com.huzz.model.SysDictItemCreateModel;
import com.huzz.model.SysDictItemQueryModel;
import com.huzz.model.SysDictItemUpdateModel;
import com.huzz.service.ISysDictItemService;
import com.huzz.util.entityutil.FieldUtil;
import com.huzz.util.entityutil.ModelUtil;
import com.huzz.util.tree.TreeBuilder;
import com.huzz.vo.SysDictItemVO;
import com.huzz.util.body.DataBox;
import com.huzz.util.body.ResultCode;
import com.huzz.util.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
* 系统字典Item-业务实现层
*
* @author 童年的纸飞机
* @since 2023-06-07 13:27
*/
@Service
@Slf4j
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements ISysDictItemService {

    /**
     * 系统字典ItemMapper
     */
    @Autowired
    private SysDictItemMapper sysDictItemMapper;

    /**
     * 根据进行ID查询SysDictItem
     * @param id
     * @return
     */
    @Override
    public SysDictItem getSysDictItemById(Integer id) {
        return sysDictItemMapper.selectById(id);
    }

    /**
     * 新增SysDictItem
     * @param model
     * @return
     */
    @Override
    @Transactional
    public boolean createSysDictItem(SysDictItemCreateModel model) {

        SysDictItem sysDictItem =  ModelUtil.transToSimilarEntity(model, SysDictItem.class);
        FieldUtil.setCreatedAndUpdateField(sysDictItem);


        return sysDictItemMapper.insert(sysDictItem) > 0;
    }

    /**
     * 更新SysDictItem
     * @param model
     * @return
     */
    @Override
    @Transactional
    public boolean updateSysDictItem(SysDictItemUpdateModel model) {
        if (sysDictItemMapper.selectById(model.getId()) == null) {
            throw new BizException(ResultCode.COMMON_FAIL.getCode(), "更新对象不存在");
        }

        SysDictItem sysDictItem = ModelUtil.transToSimilarEntity(model, SysDictItem.class);
        FieldUtil.setUpdateField(sysDictItem);

        return sysDictItemMapper.updateById(sysDictItem) > 0;
    }

    /**
     * 根据ID进行删除SysDictItem
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean deleteSysDictItemById(Integer id) {
        if (sysDictItemMapper.selectById(id) == null) {
            throw new BizException(ResultCode.COMMON_FAIL.getCode(), "删除对象不存在");
        }

        return sysDictItemMapper.deleteById(id) > 0;
    }

    /**
     * 分页查询SysDictItem列表
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @Override
    public IPage<SysDictItemVO> selectSysDictItemPage(Integer pageNum, Integer pageSize, SysDictItemQueryModel model) {
        QueryWrapper<SysDictItem> wrapper = getQueryWrapper(model);

        return TreeBuilder.builderIPageTree(sysDictItemMapper, new Page<>(pageNum, pageSize), wrapper, SysDictItemVO.class);
    }

    /**
     * 查询SysDictItem列表
     *
     * @param model
     * @return
     */
    @Override
    public List<SysDictItemVO> selectSysDictItemList(SysDictItemQueryModel model) {
        QueryWrapper<SysDictItem> wrapper = getQueryWrapper(model);

        return TreeBuilder.builderTree(sysDictItemMapper, wrapper, SysDictItemVO.class);
    }

    /**
     * 导出SysDictItem列表
     * @param request
     * @param response
     * @param model
     * @return
     */
    @Override
    public void exportSysDictItemExcel(HttpServletRequest request, HttpServletResponse response, SysDictItemQueryModel model) {
        QueryWrapper<SysDictItem> wrapper = getQueryWrapper(model);

        List<SysDictItemVO> data = sysDictItemMapper.selectSysDictItemVOList(wrapper);

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("系统字典Item列表", "SysDictItemVO"), SysDictItemVO.class, data);
        String fileName = String.format("系统字典Item_%d.xls", System.currentTimeMillis());
        response.setHeader("Content-Disposition", "attachment;Filename=" + fileName);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 批量编辑SysDictItem
     *
     * @param modelList
     * @return
     */
    @Override
    public DataBox<String> updateSysDictItemByList(List<SysDictItemUpdateModel> modelList) {
        List<SysDictItem> sysDictItemList = ModelUtil.transToSimilarList(modelList, SysDictItem.class);
        int i = 0;
        for (SysDictItem sysDictItem : sysDictItemList) {
            FieldUtil.setUpdateField(sysDictItem);
            i += sysDictItemMapper.updateById(sysDictItem);
        }

        return i > 0 ?
        DataBox.succeedBuilder("共" + i + "条记录更新成功, " + (sysDictItemList.size() - i) + "条记录更新失败") : DataBox.failedBuilder("更新失败");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public DataBox<String> deleteSysDictItemByIds(List<Integer> ids) {
        int i = sysDictItemMapper.deleteBatchIds(ids);
        return i > 0 ?
        DataBox.succeedBuilder("共" + i + "条记录被删除, " + (ids.size() - i) + "条记录删除失败") : DataBox.failedBuilder("删除失败");
    }

    /**
     * 查询条件
     * @param model
     * @return
     */
    private QueryWrapper<SysDictItem> getQueryWrapper(SysDictItemQueryModel model) {
        QueryWrapper<SysDictItem> wrapper = new QueryWrapper<>();

        // 根据 ids 进行查询
        if (model.getIds() != null && model.getIds().length > 0) {
            wrapper.lambda().in(SysDictItem::getId, model.getIds());
        }
        // 根据 更新时间区间 进行查询
        if (model.getTimeInterval() != null && model.getTimeInterval().length == 2) {
            wrapper.lambda().between(SysDictItem::getUpdateTime, model.getTimeInterval()[0], model.getTimeInterval()[1]);
        }
        // 根据 字典标识 进行查询
        if (!StringUtils.isEmpty(model.getLabel())) {
            wrapper.lambda().eq(SysDictItem::getLabel, model.getLabel());
        }
        // 根据 字典值 进行查询
        if (!StringUtils.isEmpty(model.getDictValue())) {
            wrapper.lambda().eq(SysDictItem::getDictValue, model.getDictValue());
        }
        // 根据 状态(1开启,0关闭) 进行查询
        if (null != model.getStatus()) {
            wrapper.lambda().eq(SysDictItem::getStatus, model.getStatus());
        }
        // 根据 父级id 进行查询
        if (null != model.getParentId()) {
            wrapper.lambda().eq(SysDictItem::getParentId, model.getParentId());
        }
        // 根据 所属字典id 进行查询
        if (null != model.getDictId()) {
            wrapper.lambda().eq(SysDictItem::getDictId, model.getDictId());
        }
        // 根据 排序 进行查询
        if (null != model.getSort()) {
            wrapper.lambda().eq(SysDictItem::getSort, model.getSort());
        }
        // 根据 sort 进行升序
        wrapper.lambda().orderByAsc(SysDictItem::getSort);
        // 根据 更新时间 进行降序
        wrapper.lambda().orderByDesc(SysDictItem::getUpdateTime);

        return wrapper;
    }

}